package codeTop;

public class q25 {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode preHead = new ListNode(-1);
        preHead.next = head;
        ListNode p1 = preHead;
        ListNode p2 = head;
        int num = 0;
        while (p2 != null) {
            p2 = p2.next;
            num++;
            if (num == k) {
                ListNode temp = p1.next;
                ListNode h = reverseList(p1.next, k);
                p1.next = h;
                temp.next = p2;
                p1 = temp;
                num = 0;
            }
        }
        return preHead.next;
    }
    public ListNode reverseList(ListNode head,int k) {
        ListNode p = head;
        ListNode next  = head.next;
        int num = 1;
        p.next = null;
        while (num!=k){
            ListNode temp = next.next;
            next.next = p;
            p = next;
            next = temp;
            num++;
        }
        return p;
    }
}
